\documentclass[smallextended]{svjour3}

\usepackage{supertabular}
\usepackage{multirow}
\usepackage{epsfig}
\usepackage{fancyvrb,courier}
\usepackage{verbatim}
\usepackage{color}

\newcommand{\todo}[1]{\textcolor{red}{\textbf{TODO: #1}}}

\definecolor{gray}{rgb}{0.9,0.9,0.9}

%\makeatletter\newenvironment{graybox}{%
%   \begin{lrbox}{\@tempboxa}\begin{minipage}{\columnwidth}}{\end{minipage}\end{lrbox}%
%   \colorbox{gray}{\usebox{\@tempboxa}}
%}\makeatother

\newenvironment{graybox}{}


%\renewcommand{\FancyVerbFormatLine}[1]{\colorbox{MyGray}{#1}}

\DefineVerbatimEnvironment%
  {code}{Verbatim}{numbers=left,numbersep=3pt,frame=lines,%
                   xleftmargin=7pt,fontsize=\footnotesize,%
                   framesep=2mm}
% the following is almost identical, but lets us emphasize text, 
%   label lines, etc. however, one has to remember to escape curly braces in code.
\DefineVerbatimEnvironment%
  {xcode}{Verbatim}{numbers=left,numbersep=3pt,frame=lines,%
                   xleftmargin=7pt,fontsize=\footnotesize,%
                   framesep=2mm,commandchars=\\\{\}}

\renewenvironment{keywords}{
       \list{}{\advance\topsep by0.35cm\relax\small
       \leftmargin=1cm
       \labelwidth=0.35cm
       \listparindent=0.35cm
       \itemindent\listparindent
       \rightmargin\leftmargin}\item[\hskip\labelsep
                                     \bfseries Keywords:]}
     {\endlist}

\hyphenation{XMLVM}

% \usepackage[pdftex]{hyperref}

\begin{document}

% \begin{frontmatter}

\title{Cross-Compiling Android Applications to \\ iOS and Windows Phone 7}

\author{A. Puder and O. Antebi}
\institute{San Francisco State University \\
Department of Computer Science \\
1600 Holloway Avenue \\
San Francisco, CA 94132 \\
Email: \email{\{arno$|$antebi\}@mail.sfsu.edu}}


\maketitle


\begin{abstract}
  Android is currently leading the smartphone segment in terms of
  market share since its introduction in 2007. Android applications
  are written in Java using an API designed for mobile apps.  Other
  smartphone platforms, such as Apple's iOS or Microsoft's Windows
  Phone 7, differ greatly in their native application programming
  model. App developers who want to publish their applications for
  different platforms are required to re-implement the application
  using the respective native SDK. In this paper we describe a
  cross-compilation approach, whereby Android applications are
  cross-compiled to C for iOS and to C\# for Windows Phone 7. We
  describe different aspects of our cross-compiler, from byte code
  level cross-compilation to API mapping. A prototype of our
  cross-compiler called XMLVM is available under an Open Source
  license.
\end{abstract}

% \end{frontmatter}

\begin{keywords}
Android, iOS, WP7, Cross-Compilation.
\end{keywords}


%\IEEEpeerreviewmaketitle



\section{Introduction}
%% 1. let's start immediately with the problem 
%%    and push android intro to sec 2

Striving to increase dissemination, most developers of mobile applications
aspire to extend their applications' availability to many different smartphone
platforms.  However, %as demonstrated in section \ref{SEC_OVERVIEW},
targeting multiple smartphone platforms requires significant skill
sets and efforts. This is mainly due to a great difference in
smartphone platforms' development models of native applications, in
spite of similar hardware capabilities.  For example, the Android
software stack employs Java as a programming language, whereas
applications for the iOS platform are written in Objective-C and
applications for Windows Phone 7 platform are written in C\# or
VisualBasic.  Moreover, Android's API for application life-cycle,
device management and UI programming differs greatly from iOS and
Windows Phone 7's APIs.

%% 2. continue immediately with introducing our solution

This paper introduces the XMLVM framework \cite{puder:10,puder:11} - a
cross-compilation solution that only assumes familiarity with a
canonical platform, chosen to be the Android software stack.  Not only
does XMLVM cross-compile applications on a language level, but it also
maps APIs between different platforms.  Thus, application developers
may use XMLVM's toolchain to cross-compile an Android application to
other smartphones, such as iOS or WP7, even without any native iOS or
WP7 skills. Another benefit of XMLVM is that only one code-base needs
to be maintained by application developers.

%% 2.1 why android?

The rationale behind the choice of Android as a canonical platform is
based on the assumption that there is a wide skill set for the Java
programming language and that there are powerful tools to develop in
Java, in comparison to Objective-C and C\# used for iOS and WP7
development, respectively.  Moreover, Android was specifically
designed to offer applications the means to adapt to a wider range of
mobile devices.  Hence, we believe that it serves as a natural
umbrella over other smartphone platforms.  Furthermore, the
XMLVM toolchain is able to benefit from many open source tools offered
for the Android software stack, such as tools for API mapping and for
transformation of Oracle's stack-based virtual machine instructions
\cite{Lindholm:99} to register-based byte code instruction set
introduced by the Dalvik virtual machine \cite{dalvik:dx} to allow
generation of more efficient code in the target language.
%Other
%approaches and related work are described in section
%\ref{SEC_RELATED_WORK}.

%% 3. structure:
% AP: I prefer the old ending of Section 1. We should give a squential
% section-by-section overview of the rest of the paper which this
% paragraph doesn't do. Furthermore, the (still missing) figure
% that is referenced here is somewhat related to the toolchain
% figure later in the paper.

%As illustrated in figure \ref{FIG_LAYERS}, the XMLVM framework
%consists of three layers: the lower layer is discussed in section
%\ref{SEC_BYTE_CODE} and provides language level cross-compilation of
%Java byte codes used on the Android platform into native code on the
%target platform, such as C\# on the WP7 and C on iOS.  The middle
%layer, discussed in section \ref{SEC_J2SE}, cross-compiles Java API by
%applying the language cross-compilation to Apache Harmony's
%Java implementation of the JDK.  These two layers are complemented by
%mapping user interface API from Android to the target platforms on the
%topmost layer, as outlined in section \ref{SEC_API_MAPPING}.  In Section
%\ref{SEC_PROTOTYPE}, we discuss our prototype implementation of this
%framework as well as an application that was cross-compiled using our
%toolchain.  Finally, Section \ref{SEC_CONCLUSIONS} provides a
%conclusion and an outlook to future work.
%% i think we should provide the link somewhere here, rather than at the end of the paper:
% XMLVM is available under an open source license at
% \href{http://xmlvm.org}{http://xmlvm.org}.

%% old structure paragraph:

This paper is organized as follows: Section \ref{SEC_OVERVIEW} gives
an overview of different development models of Android, iOS and WP7,
thereby providing the motivation for our work. It is followed by a
discussion of related work in Section \ref{SEC_RELATED_WORK}.  In
Section \ref{SEC_BYTE_CODE} we explain how XMLVM translates Java byte
codes to the C and C\# programming languages.  Section \ref{SEC_J2SE}
describes how an applications dependencies to the J2SE runtime library
are resolved.  Section \ref{SEC_API_MAPPING} focuses on the API
mapping from Android to iOS and WP7.  In Section \ref{SEC_PROTOTYPE},
we discuss our prototype implementation as well as an application that
was cross-compiled using our toolchain.  Finally, Section
\ref{SEC_CONCLUSIONS} provides a conclusion and an outlook to future
work.


\section{Overview of Android, iOS, and Windows Phone 7}
\label{SEC_OVERVIEW}

%% my suggestion for the logic of this section is:
%% 1. start immediatly with the goal of the section
%%    IMHO the goal is not to show the differences, but rather to argue that
%%    it is difficult to target multiple platforms. instead, showing the diffs is
%%    our method to support the goal argument.
%% 2. introduce the table to support this goal
%% 3. provide some background on each platform 
%%    (some of which is pushed from the old introduction section)
%% 4. give more details about the diffs in devel languages 
%% 5. give more details about the diffs in API.
%%    this is done by introducing the APIs in the respective subsections 

In this section we demonstrate the wide skill sets and efforts needed
to target different smartphone platforms.  To this end, we show that
smartphone platforms differ greatly in their native application
development models, although they share relatively similar
hardware capabilities.  This is illustrated in Table
\ref{TAB_SMARTPHONE_COMPARISON}, which provides a side by side
comparison of the Android-based Nexus S sold by Google, Apple's iPhone
4, and Samsung's Omnia 7 which uses Microsoft's WP7.

%% 3. introducing android/wp7 (pushed from intro section):

Initially developed by Android Inc (purchased by Google in 2005) and
later by the Open Handset Alliance, Android
provides % also consider simple 'is' and 'supports' instead of 'advocates'
a mobile operating system running on the Linux kernel.  Android is not
exclusively targeting smartphones, but is also available for netbooks,
tablets and settop boxes. In contrast, iOS and WP7
are both proprietary platforms developed by Apple and Microsoft,
respectively. iOS is only available for Apple devices, whereas WP7 is
licensed by various smartphone manufacturers meeting hardware
requirements stipulated by Microsoft. iOS and WP7 apps are offered
exclusively from Apple's AppStore and Microsoft's Marketplace,
respectively, whereas Android Apps are offered both through the
Android Market and from third-party websites.

%% 4. diffs in programming languages:

With respect to the development language, Android employs Java,
whereas iOS uses Objective-C and WP7 is based on .NET using
either C\# or VisualBasic. While Java and C\# are relatively similar,
their respective object models differ in subtle ways as demonstrated
in a subsequent section.  For instance, C\# features true generics
and also supports events and delegates as part of its object model in
contrast to Java.  iOS on the other hand is based on Objective-C.
While Java and C\# feature strong typing and garbage collection, the
version of Objective-C used on iOS supports dynamic typing, but no
garbage collection.

%% 5. diffs in APIs:

Furthermore, Android, iOS and WP7 also differ greatly in their APIs
for user interface, application lifecycle and device management.  To
better highlight the different programming environments, the following
three sections will show a simple application for each smartphone
platforms using their respective native programming language. The
application allows to enter a name and upon pressing a button, the
name will be echoed in a label. This application is more involved
compared to a simple ``Hello World'', but the purpose is to provide a
brief introduction to the programming abstractions employed by the
respective platform and also to demonstrate the heterogeneity of
smartphone application development.


\begin{table}
\begin{center}
\begin{tabular}{|l||p{2.9cm}|p{2.9cm}|p{2.9cm}|}
\hline
                 & \multicolumn{1}{|c|}{\textbf{Nexus S}}
                 & \multicolumn{1}{c|}{\textbf{iPhone 4}}
                 & \multicolumn{1}{c|}{\textbf{Omnia 7}} \\ \hline \hline
OS               & Linux
                 & iOS
                 & Windows CE \\ \hline
CPU              & Hummingbird S5PC110, 1 GHz
                 & Apple A4, 1 GHz
                 & Snapdragon QSD8250, 1 GHz \\ \hline
RAM              & 512 MB
                 & 512 MB
                 & 512 MB \\ \hline
Sensors          & Accelerometer, GPS, proximity, ambient light, compass.
                 & Accelerometer, GPS, proximity, ambient light, compass.
                 & Accelerometer, GPS, proximity, ambient light, compass. \\ \hline
IDE              & Eclipse
                 & Xcode
                 & VisualStudio \\ \hline
Language         & Java
                 & Objective-C
                 & C\#, VisualBasic \\ \hline
GUI              & Android
                 & Cocoa Touch
                 & WP7 \\ \hline
VMs              & Allowed
                 & Not allowed
                 & Only .NET \\ \hline
License          & Open Source
                 & Proprietary
                 & Proprietary \\ \hline
\end{tabular}
\end{center}
\caption{Smartphone comparison.}
\label{TAB_SMARTPHONE_COMPARISON}
\end{table}

%\begin{figure}[htb]
%\begin{center}
%\includegraphics[width=3.5cm]{sayhello-screenshot}
%\caption{\label{FIG_SAYHELLO_SCREENSHOT} Android ``Say Hello'' Application.}
%\end{center}
%\end{figure}


\subsection{Android}
\label{SEC_ANDROID}

An Android application consists of a set of so-called
\emph{activities}. An activity is a user interaction that may have one
or more input screens. An example for an activity is the selection of a
contact from the internal address book. The user may flip through the
contact list or may use a search box. These actions are combined to form an
activity. Activities have a well-defined life cycle and can be invoked
from other activities (even activities from other applications). The
sample application that we introduce here 
consists of a single activity which 
uses three widgets: a text
input box, a label, and a button. Upon clicking the button, the name
from the text input box is read and echoed with a greeting in the
label.
%Figure \ref{FIG_SAYHELLO_SCREENSHOT} shows a screenshot of the
%Android version of this application.
The following code is the
complete implementation of the Android application:

\begin{xcode}[label=Java (using Android API)]
public class SayHello extends Activity \{
  @Override
  public void onCreate(Bundle savedState) \{
    super.onCreate(savedState);
    LinearLayout panel = new LinearLayout(this);
    panel.setOrientation(LinearLayout.VERTICAL);
    LayoutParams params =
          new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                                        LayoutParams.WRAP_CONTENT);
    params.setMargins(10, 10, 10, 10);
    final EditText box = new EditText(this);
    box.setLayoutParams(params);
    panel.addView(box);
    final TextView label = new TextView(this);
    label.setLayoutParams(params);
    label.setGravity(Gravity.CENTER_HORIZONTAL);
    panel.addView(label);
    Button button = new Button(this);
    button.setLayoutParams(params);
    button.setText("Say Hello");
    button.setOnClickListener(
      new OnClickListener() \{

        @Override
        public void onClick(View view) \{
            label.setText("Hello, " + box.getText() + "!");
        \}

      \});
    panel.addView(button);
    setContentView(panel);
  \}
\}
\end{xcode}

Every Android application needs to designate a main activity whose
implementation has to be derived from the base class \texttt{Activity}.
The main entry point of an activity is the method \texttt{onCreate()} that
also signals the creation of the activity. In case the activity was
active at an earlier point in time, the saved state of the previous
incarnation is passed as an argument to \texttt{onCreate()}. Inside
the \texttt{onCreate()} method, a \texttt{LinearLayout} is
instantiated that acts as a container and allows to automatically
align its children vertically (line 5).
Next, some general layout parameters are created (lines 7--10) that
define padding of 10 pixels, tell that a widget's horizontal size
should use up all available space of the parent
(\texttt{FILL\_PARENT}) and its vertical size should be the widgets
natural size (\texttt{WRAP\_CONTENT}). Those layout parameters are
applied to all widgets created subsequently. 

Three widgets are created
in total: a text input box (line 11), a label (line 14), and a button
(line 18). A click listener is added to the button (line 21) in the
form of an instance of an anonymous class. Whenever the button is
clicked, the click listener will read the name from the text input box
and echo a greeting via the label. The remaining code of the ``Say
Hello'' application defines the view hierarchy by adding the widgets
to the \texttt{LinearLayout} and then setting the
\texttt{LinearLayout} as the main content view (line 31).

Besides a variety of widgets, Android also allows the declarative
description of user interfaces. XML files describe the layout of a
user interface which not only simplifies internationalization but also
allows to render the user interface on different screen resolutions.


\subsection{iOS}

This sections shows how the same ``Say Hello'' application can be
implemented for iOS.  The primary language offered by Apple for iOS
development is Objective-C, hence the ``Say Hello'' application for
this platform is written in that language. Apple prohibits general
background processes per license agreement of its SDK which implies
that the life cycle of an application is much simpler compared to
Android.  Applications have to be derived from base class
\texttt{UIApplication} and the entry point is a method called
\texttt{applicationDidFinishLaunching}. The following code
demonstrates ``Say Hello'' for iOS:

\begin{xcode}[label=Objective-C (using iOS API)]
@interface SayHello : UIApplication \{
  UILabel*     helloLabel;
  UITextField* editName;
\}

- (void) applicationDidFinishLaunching:(NSNotification*) n;
- (void) buttonClicked;
@end

@implementation SayHello

- (void) applicationDidFinishLaunching:(NSNotification*) n
\{
  UIScreen* screen = [UIScreen mainScreen];
  CGRect r = [screen applicationFrame];
  UIWindow* window = [[UIWindow alloc] initWithFrame: r];
  [window setBackgroundColor:UIColor.whiteColor];
  r.origin.x = r.origin.y = 20;
  r.size.width = 280;
  r.size.height = 30;
  editName = [[UITextField alloc] initWithFrame:r];
  [editName setBorderStyle:UITextBorderStyleBezel];
  [window addSubview:editName];
  r.origin.y += 50;
  helloLabel = [[UILabel alloc] initWithFrame:r];
  [helloLabel setTextAlignment: UITextAlignmentCenter];
  [window addSubview:helloLabel];
  r.origin.y += 50;
  UIButton* button =
      [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [button setFrame:r];
  [button setTitle:@"Say Hello"
          forState:UIControlStateNormal];
  [button addTarget:self action:@selector(buttonClicked)
          forControlEvents:UIControlEventTouchUpInside];
  [window addSubview:button];
  [window makeKeyAndVisible];
\}

- (void) buttonClicked
\{
  NSMutableString* greeting =
        [NSMutableString stringWithString:@"Hello, "];
  [greeting appendString:editName.text];
  [greeting appendString:@"!"];
  [helloLabel setText:greeting];
\}

@end
\end{xcode}

Objective-C distinguishes between declaration (line 1) and definition
(line 10) of a class, similar to C++. Since we will need to access the
text input box as well as the label later in the implementation of
``Say Hello'', pointers to both widgets are stored in instance member
variables (lines 2 and 3). Square brackets in Objective-C denote a
method invocation. The first argument represents the target of the
invocation followed by the named arguments. Object instantiation
always happens in two steps in Objective-C: first sufficient memory is
allocated via class method \texttt{alloc} and then followed by some
variation of an \texttt{init} method that initializes the newly
created instance. Since Objective-C is a strict superset of the C
programming language, references to objects are regular C pointers.

In the program above, the dimensions of the main screen are first
retrieved (lines 14--15). Because of the top-level status bar of the
iPhone, the origin of the \texttt{CGRect} returned in line 15 will be
(0, 20).  \texttt{UIWindow} represents the top-level window that the
application will occupy. One difference to the Android version of
``Say Hello'' is that iOS does not feature a layout manager.  All
widgets need to be sized and positioned individually in terms of
absolute coordinates relative to the \texttt{UIWindow} instance.
Conceptually, the iOS version follows the same structure as its
Android counterpart: the text input box (line 21), the label (line 25)
and the button (line 29) are created and manually placed on the
window. Many explicit settings are necessary. E.g., by default the
main window would be black and so would be the text input box,
effectively rendering it invisible. Only with the explicit settings
shown above the UI gets its familiar iOS look-and-feel.

Event listeners are implemented in iOS via delegates. Due to the
dynamic typing of Objective-C, any object can serve as an event
listener, provided it implements the proper call-back. In line 34, a
delegate is attached to the button. The target is the
\texttt{UIApplication} object itself (\texttt{self}) and the method to
be invoked is \texttt{buttonClicked} (the name of the method can be
arbitrarily chosen). The name of the method is passed via the
\texttt{@selector()} expression of Objective-C. Note that because of
this it is impossible to perform compile-time checks: if, for example,
the name of the method \texttt{buttonClicked} in line 34 were
misspelled, an error would only occur at runtime. The
\texttt{makeKeyAndVisible} method (line 37) finally makes the
\texttt{UIWindow} instance the main window and makes it visible.


\subsection{Windows Phone 7}
\label{SEC_SAY_HELLO_WP7}

This sections shows how the same ``Say Hello'' application can be
implemented for WP7.  The primary languages offered by Microsoft for
WP7 development are C\# and VisualBasic, hence the ``Say Hello''
application for this device has to be written in one of those
languages.


\begin{xcode}[label=C\# (using WP7 API)]
public class SayHello : Application \{
  private TextBox box = new TextBox();
  private TextBlock label = new TextBlock();
  private Button button = new Button();

  public SayHello() \{
    this.Startup += new StartupEventHandler(Main);
  \}

  public void Main(object sender, StartupEventArgs args) \{
    label.Foreground = new SolidColorBrush(Colors.White);
    label.Margin = new Thickness(10);
    button.Content = "Say Hello";
    button.Click += new RoutedEventHandler(Click);
    button.Margin = new Thickness(10);
    box.Margin = new Thickness(10);
    StackPanel panel = new StackPanel();
    panel.Children.Add(box);
    panel.Children.Add(label);
    panel.Children.Add(button);
    this.RootVisual = panel;
  \}

  public void Click(object sender, RoutedEventArgs args) \{
    label.Text = "Hello, " + box.Text + "!";
  \}
\}
\end{xcode}

A WP7 application class needs to be derived from a base class called
\texttt{Application}. Its constructor adds a new event handler to the
\texttt{Startup} property (line 7) that will result in method
\texttt{Application.Main()} to be invoked (line 10). Analogous to the
Android version, the three widgets of the ``Say Hello'' application
are called \texttt{TextBox}, \texttt{TextBlock} and \texttt{Button}
(lines 2--4). Method \texttt{Main()} first sets various properties of
those widgets including a 10-pixel margin and a click listener for the
button (line 14). Just as with the startup property, the click
listener is added via the overloaded \texttt{+=} operator in C\#. If
the user clicks the button, method \texttt{Click()} of class
\texttt{Application} will be invoked. The vertical alignment of the
three widgets is realized in WP7 by a so-called \texttt{StackPanel}
(line 17).



\section{Related Work}
\label{SEC_RELATED_WORK}

Several frameworks promise to facilitate the development of
cross-platform applications. In the following we briefly discuss the
approach taken by PhoneGAP, MonoTouch, and Adobe AIR. Each framework
will be classified with regards to the mobile platforms it supports,
the programming languages it offers, the API it uses, the IDE it can
be used with and finally the license under which it is released.

PhoneGAP is an Open Source project that addresses web developers who
wish to write mobile applications. It is available for iOS, Android,
BlackBerry and the Palm Pre. Applications need to be written in
JavaScript/HTML/CSS. But instead of downloading the application from a
remote web server, the JavaScript is bundled inside a native
application.  E.g., for iOS devices a generic startup code written in
Objective-C will instantiate a full-screen web widget via class
\texttt{UIWebView}  as depicted in Figure \ref{FIG_PHONEGAP}.  Next
the JavaScript that is embedded as data in the native application is
injected into this web widget at runtime. Special protocol handlers
allow the communication between JavaScript and the native layer. All
iOS widgets are rendered using HTML/CSS mimicking the look-and-feel of
their native counterparts.  PhoneGAP supports a common API for sensors
such as the accelerometer.  Platform-specific widgets have their own
API. PhoneGAP is available under the MIT Open Source license at
\texttt{http://phonegap.com}.


\begin{figure}[htb]
\begin{center}
\includegraphics[width=7cm]{phonegap}
\caption{\label{FIG_PHONEGAP} Web Application Development Model.}
\end{center}
\end{figure}


Xamarin (formerly Novell) offers with MonoTouch a .NET based framework
for mobile applications. MonoTouch allows iOS applications to be
written in C\#. The C\# iOS API is mapped one-for-one from the Cocoa
Touch/Objective-C API. MonoTouch is able to read so-called XIB (Xcode
InterfaceBuilder) files created by Xcodes InterfaceBuilder.
Applications written in C\# are compiled to ARM instructions utilizing
the Open Source project Mono. Since Apple does not permit the
installation of a virtual machine, C\# applications are compiled using
AOT (Ahead-of-Time) compilation instead of JIT (Just-in-Time)
execution.  Xamarin recently released a .NET based framework for
Android called MonoDroid that allows Android applications to be
written in C\#.  MonoTouch and MonoDroid are available under a
commercial license at \texttt{http://ios.xamarin.com}.

\begin{table*}
\begin{center}
\begin{tabular}{|l||p{2cm}|p{2cm}|p{2cm}|p{2cm}|}
\hline
            & \multicolumn{1}{|c|}{\textbf{PhoneGAP}}
            & \multicolumn{1}{c|}{\textbf{MonoTouch}}
            & \multicolumn{1}{c|}{\textbf{Adobe AIR}}
            & \multicolumn{1}{c|}{\textbf{XMLVM}} \\ \hline \hline
Platforms   & iOS, Android, Blackberry, Palm Pre
            & iOS
            & iOS
            & iOS, Android, WP7  \\ \hline
Language    & JavaScript
            & C\#
            & ActionScript
            & Java \\ \hline
API         & Common Sensor API
            & iOS-only
            & Graphics-only
            & Android API mapped to iOS, WP7 \\ \hline
IDE         & Xcode
            & MonoDevelop
            & N/A
            & Eclipse \\ \hline
License     & Open Source
            & Commercial
            & Commercial
            & Open Source \\ \hline
\end{tabular}
\end{center}
\caption{Comparison of Cross-Platform Frameworks.}
\label{TAB_CROSS_PLATFORM_COMPARISON}
\end{table*}


Another cross-platform framework is the Adobe Integrated Runtime (AIR) for iOS development.
Similar to MonoTouch, Adobe AIR includes an AOT compiler based on the
LLVM compiler suite that translates ActionScript 3 to ARM
instructions. This facilitates porting of existing Flash applications
while not relying on an installation of a Flash player on the iOS
device. AIR offers API based on ActionScript to the device's sensors,
but does not provide access to the native iOS widgets which limits AIR
applications to games. As the only framework, AIR does not depend on
Apple's Xcode SDK. AIR applications can be written under Windows. AIR
is available under a commercial license at
\texttt{http://www.adobe.com/products/air/}.

Table \ref{TAB_CROSS_PLATFORM_COMPARISON} summarizes the
distinguishing factors of the various cross-platform frameworks
introduced in this section. XMLVM is similar in the respect that it
offers one programming language (Java) for different mobile devices.
It also includes an AOT compiler to translate Java to native
applications in order to avoid the installation of a Java virtual
machine on the target platform. In contrast to other cross-platform
frameworks, XMLVM relies on the Android API for application
development. Instead of creating a new API for various
functionalities, XMLVM makes use of the Android API that is mapped to
the target platform. Besides sensor API, XMLVM is also capable of
mapping Android widgets and layout managers such the ones used in the
``Say Hello'' application. Both the cross-compilation on a
language-level as well as the API mapping is discussed in detail in
the following sections.



\section{Byte Code Level Cross-Compilation}
\label{SEC_BYTE_CODE}

% In the following examples we view the register-based format of
% XMLVM  (\texttt{XMLVM}
% in Figure \ref{FIG_FRAMEWORK}) as a separation of the frontend from the backends.  
% As we illustrate in the next section,
% generation of high-level code in the target language, which for our
% backend is C\#, is then a matter of a simple XSL transformation.
% Other backends have also been considered in earlier work, of which the
% most complete is the C backend used to build complex iOS applications.

% In this section we introduce our language-level cross-compiler, 
% as a backend extension of a general flexible byte code level cross-compiler.
% The latter is 
% named XMLVM due to its internal representation of
% byte code instructions of the virtual machine via appropriate XML tags. 

In this section we introduce our language-level cross-compiler (Figure
\ref{FIG_BYTE_CODE_LEVEL}). Rather than cross-compiling source code of
high-level programming languages as done by other tools, XMLVM chooses
to cross-compile Java byte codes.  That is, the source code is first
compiled to Java byte codes via a regular Java compiler, and then fed
into the XMLVM tool.  One advantage of this approach is that some
high-level language features such as generics are already simplified
in the low-level byte code instructions.  Moreover, the byte codes
themselves are much easier to parse than Java source code.
Furthermore, XMLVM can leverage byte code optimizations done by the
Java compiler.

\begin{figure}[htb]
\begin{center}
\includegraphics[width=9cm]{framework}
\caption{\label{FIG_BYTE_CODE_LEVEL} XMLVM byte code level cross compilation.}
\end{center}
\end{figure}

In Section \ref{SEC_FRONTEND} we describe the frontend XML
representation of byte codes.  Section \ref{SEC_C_BACKEND}
describes the C backend needed for iOS pipeline, whereas Section
\ref{SEC_CSHARP_BACKEND} describes the C\# backend needed for the WP7
pipeline.  Throughout this section, we illustrate XMLVM's approach
with the following example of simple Java class \texttt{Account},
whose method \texttt{deposit()} adds a given amount to the
\texttt{balance} of an account:

\noindent
\begin{graybox}
\begin{xcode}[label=Account.java]
public class Account \{
    int balance;
    // ...
    public void deposit(int amount) \{
        balance += amount;
    \}
\}
\end{xcode}
\end{graybox}

\subsection{Frontend}
\label{SEC_FRONTEND}

The source code is first compiled to Java byte codes via a regular
Java compiler resulting in a class file, and then fed into our
XMLVM tool.  The byte codes are then transformed from Java's
stack-based byte code instructions \cite{Lindholm:99} to more
efficient register-based instructions introduced by Dalvik
\cite{dalvik:bytecodes}. This transformation has been studied in
\cite{Davis:03,Shi:08}; in fact, one of the advantages of choosing
Android as the canonical platform is that XMLVM can utilize the
open-source Dalvik eXchange (DX) \cite{dalvik:dx} for this task.

These byte code instructions of the virtual machine are represented as
XML tags and attributes using JDOM \cite{jdom}, with additional tags
to represent class, field and method definitions, method signatures,
etc.  In fact, the framework is named XMLVM due to this internal
representation.  For instance, XMLVM represents the virtual machine
instructions of the aforementioned class \texttt{Account} via the
following XML document:

\noindent
\begin{graybox}
\begin{xcode}[label=XMLVM]
<vm:xmlvm ...>
  <vm:class name="Account" ...>\label{VM_CLASS}
    <vm:field name="balance" type="int" />\label{VM_FIELD}
    <!-- ... -->
    <vm:method name="deposit" ...>\label{VM_METHOD}
      <vm:signature>\label{VM_SIGNATURE}
        <vm:parameter type="int" />
        <vm:return type="void" />
      </vm:signature>
      <dex:code register-size="3">\label{DEX_CODE}
        <dex:var name="this" register="1"\label{DEX_VAR1}
                 type="Account" />
        <dex:var register="2" param-index="0"\label{DEX_VAR2}
                 type="int" />
        <dex:iget member-name="balance"\label{DEX_IGET}
                  vx="0" vx-type="int" 
                  vy="1" vy-type="Account" .../>
        <dex:add-int vx="0" vy="0" vz="2" />\label{DEX_ADD_INT}
        <dex:iput member-name="balance"\label{DEX_IPUT}
                  vx="0" vx-type="int" 
                  vy="1" vy-type="Account" .../>
        <dex:return-void />
      </dex:code>
    </vm:method>
  </vm:class>
</vm:xmlvm>
\end{xcode}
\end{graybox}
On the top-level, there are tags to represent the class definition
(line \ref{VM_CLASS}), field definitions (line \ref{VM_FIELD}), method
definitions (line \ref{VM_METHOD}) and their signatures (line
\ref{VM_SIGNATURE}).  The attribute \texttt{register-size} (line
\ref{DEX_CODE}) specifies the number of registers required to execute
the method.  Registers can only store integers, floats, doubles, longs
and object reference. The latter are always of type
\texttt{java.lang.Object}, while the actual types are stored in XML
attributes. Shorter primitive types such as bytes and shorts are
sign-extended to 32-bit integers.

Described hereafter, the children of the tag \texttt{$<$dex:code$>$}
(line \ref{DEX_CODE}) represent the byte code instructions for the
method \texttt{deposit()}.  Upon entering a method, the last $n$
registers are automatically initialized with the $n$ actual
parameters.  Since the method \texttt{deposit()} has three registers
labeled 0 to 2, register 2 is initialized (line \ref{DEX_VAR2}) with
the single actual parameter of that method (the amount).  The implicit
\texttt{this}-parameter counts as a parameter and will therefore be
copied to register 1 (line \ref{DEX_VAR1}).  The byte code
instructions read and write to various registers that are referred to
via attributes \emph{vx}, \emph{vy}, and \emph{vz}, where \emph{vx}
usually designates the register that stores the result of the
operation. The first instruction \texttt{$<$dex:iget$>$}
(\emph{instance get}) loads the content of the field \texttt{balance}
of the account object referenced by register 1 into register 0 (line
\ref{DEX_IGET}).  The \texttt{$<$dex:add-int$>$} (\emph{add integer})
instruction (line \ref{DEX_ADD_INT}) adds the integers in registers 0
(the current balance) and 2 (the actual parameter) and store the sum
in register 0. This instruction performs the operation $vx = vy + vz$.
The \texttt{$<$dex:iput$>$} (\emph{instance put}) instruction (line
\ref{DEX_IPUT}) performs the opposite of \texttt{$<$dex:iget$>$}: the
content of register 0 is stored in field \texttt{balance} of the
object referenced by register 1.

As we demonstrate in the following subsections, this XML
representation enables a flexible generation of high-level code in the
target language (C, C\#). This is achieved by applying XSL \cite{xsl}
transformations using Saxon \cite{saxon} which simulate the
register-based virtual machine in the target language. To this end,
registers are mapped to union-like variables in the target language
containing the different data types that these registers may hold.
The effect of each byte code instruction is then mapped to these
variables.  Thus, the language-level cross-compiler can easily support
multiple native language back-ends, by application of different
stylesheets, as illustrated in Figure \ref{FIG_BYTE_CODE_LEVEL}.

\subsection{C Backend}
\label{SEC_C_BACKEND}

Apple mandates Objective-C as the development language for iOS. Since
Objective-C is a strict super-set of the C programming language, the
XMLVM backend for iOS generates C because of its portability.  When
cross-compiling Java bytecodes to C, we map individual registers to C
variables. To this end, we introduce a C-union that reflects the
different data types that these registers may contain:

\noindent
\begin{graybox}
\begin{xcode}[label=C]
typedef union \{
    JAVA_OBJECT o;
    JAVA_INT    i;
    JAVA_FLOAT  f;
    JAVA_DOUBLE d;
    JAVA_LONG   l;
\} XMLVMElem;
\end{xcode}
\end{graybox}

Variables representing registers are automatically generated by XSL
templates during the code generation process.  They are always
prefixed with \texttt{\_r} followed by the register number, and their
definition is based on \texttt{XMLVMElem}.  With the help of these
variables, it is possible to map the effect of individual byte code
instructions to the target language using XSL templates.  As an
example, the following XSL template shows how the aforementioned byte
code instruction \texttt{$<$dex:add-int$>$} is mapped to C source
code:

\noindent
\begin{graybox}
\begin{xcode}[label=XSL template]
<xsl:template match="dex:add-int">
    <xsl:text>_r</xsl:text>
    <xsl:value-of select="@vx"/>
    <xsl:text>.i = _r</xsl:text>
    <xsl:value-of select="@vy"/>
    <xsl:text>.i + _r</xsl:text>
    <xsl:value-of select="@vz"/>
    <xsl:text>.i;</xsl:text>
</xsl:template>
\end{xcode}
\end{graybox}

Because of the declarative nature of XSL, the above template will
``fire'' whenever the \texttt{$<$dex:add-int$>$} instruction is
encountered in the XML document. The children of the template define
the code that will be generated in response to the specific byte code
instruction.  Applying all XSL templates to the XMLVM of the class
\texttt{Account} shown earlier yields the following C source code for
the method \texttt{deposit()}:

\noindent
\begin{graybox}
\begin{xcode}[label=Generated C]
//...
void Account_deposit___int(JAVA_OBJECT me, JAVA_INT n1) \{
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    _r1.o = me;
    _r2.i = n1;
    _r0.i = ((Account*) _r1.o)->fields.balance;
    \textbf{_r0.i = _r0.i + _r2.i;}\label{C_ADD_INT}
    ((Account*) _r1.o)->fields.balance = _r0.i;
    return;
\}
\end{xcode}
\end{graybox}

In particular, note that the code in line \ref{C_ADD_INT} was
generated by the XSL template for the \texttt{$<$dex:add-int$>$}
instruction explained earlier.  Every method of a class is mapped to a
C function whose name is mangled from the class and method name as
well as the method's signature. For each class, a so-called \emph{Type
  Information Block} (TIB) is generated (see Figure
\ref{FIG_TIB}). The TIB contains all relevant meta-data about a class
such as fully qualified name, base class, all implemented interfaces,
etc. When a class is instantiated, enough memory is allocated for all
the instance members plus a pointer to the TIB. Since XMLVM
cross-compiles byte code to C, there is no notion of dynamic class
loading as usually found in a Java VM. A particular challenge poses
the Java reflection API. In order to support dynamic method
invocations via the reflection API, XMLVM creates method dispatchers
for each class.

\begin{figure}
\centering
{\epsfig{file=tib, width=10cm}}
\caption{\label{FIG_TIB} Type Information Block.}
\end{figure}

Since XMLVM cannot load classes dynamically at runtime, all classes
that are needed for an application need to be known at compile time.
As will be discussed in detail in a subsequent section, XMLVM performs
a static dependency analysis to determine the transitive closure of
all referenced classes. Since XMLVM operates under the \emph{Closed
  World Assumption} (i.e., all referenced classes are known \emph{a
  priori}) it is possible to perform powerful compile-time
optimizations, especially for method invocations. Java distinguishes
between two different dynamic method invocations on byte code level:
\texttt{$<$dex:invoke-virtual$>$} is used for calling methods on an
object, whereas \texttt{$<$dex:invoke-interface$>$} is used to invoke
methods via an interface type. The reason for two different invoke
instructions has to do with the fact that Java allows single
inheritance for classes but multiple inheritance for interfaces. For
the former it is possible to build a so-called vtable which
essentially is an array of function pointers. An
\texttt{$<$dex:invoke-virtual$>$} instruction references a vtable
index to the appropriate implementation of a method. Because of the
Closed World Assumption it is known at compile-time whether a method
is overridden in a derived class or not. If a method is not
overridden, it can be called directly without the need of allocating
an entry in the vtable.

%AP: The following paragraph reflects the status quo in the C backend
% and does not need any revisions.
%\todo{Revise this based on Markus' optimization}

Similar optimizations can be done for
\texttt{$<$dex:invoke-interface$>$}. Here XMLVM computes an itable
(analogous to the vtable) for interface methods.  Because of the
Closed World Assumption it is possible to compute an itable that can
be indexed via one indirection. The technique is known as selector
coloring and is described in \cite{dixon:89}. The overhead of
performing an \texttt{$<$dex:invoke-interface$>$} with XMLVM's C
backend is identical to performing an
\texttt{$<$dex:invoke-virtual$>$}.

The following code excerpt shows how a method invocation in Java (line
2) is represented in XMLVM (lines 5--10) and how it is mapped to C
code:  

\noindent
\begin{graybox}
\begin{xcode}
// Java
account.deposit(amount);

<!-- XMLVM -->
<dex:invoke-virtual class-type="Account" method="deposit" register="0">
  <dex:parameters>
    <dex:parameter type="int" register="1" />
    <dex:return type="void" />
  </dex:parameters>
</dex:invoke-virtual>

// C (direct)
Account_deposit___int(_r0.o, _r1.i);\label{C_DIRECT_CALL}

// C (via vtable)
typedef *(void (*)(JAVA_OBJECT, JAVA_INT)) FPTR;\label{C_FPTR}
(FPTR ((Account*) _r0.o)->tib->vtable[11])(_r0.o, _r1.i);\label{C_VTABLE}
\end{xcode}
\end{graybox}

If the method \texttt{deposit()} is not overridden in a derived class,
it can be invoked via a direct function call (line
\ref{C_DIRECT_CALL}).  Otherwise the method \texttt{deposit()} needs
to be invoked via a vtable.  First, \texttt{FPTR} is defined as a
function pointer of the proper type that reflects the signature of the
method \texttt{deposit()} (line \ref{C_FPTR}), then the vtable is
accessed via the TIB (line \ref{C_VTABLE}). In this particular example
the function pointer for the method \texttt{deposit()} is stored at
vtable index 11.


\subsection{C\# Backend}
\label{SEC_CSHARP_BACKEND}

Since WP7 only permits C\# and VisualBasic as development languages,
the C backend described in the previous section cannot be leveraged
for this platform. For this reason XMLVM features a C\# backend that
emits C\# source code.  The flexibility of the XMLVM framework is best
seen in the similarity of the C\# backend to the aforementioned C
backend.  Again the strategy is to use XSL templates to map individual
registers to C\# variables, and to map the effect of individual byte
code instructions to these C\# variables.  Applying all XSL templates
of the C\# backend to the XMLVM of the class \texttt{Account} shown
earlier yields the following C\# source code for the method
\texttt{deposit()}:

\noindent
\begin{graybox}
\begin{xcode}[label=Generated C\# for deposit()]
//...
public virtual void deposit(int n1) \{
    org.xmlvm.Element _r0;\label{CSHARP_PRIMITIVE_TYPE}
    System.Object     _r1_o;\label{CSHARP_OBJ_REF}
    org.xmlvm.Element _r2;
    //...
    _r1_o = this;
    _r2.i = n1;
    _r0.i = ((Account) _r1_o).balance;
    \textbf{_r0.i = _r0.i + _r2.i};\label{CSHARP_ADD_INT}
    ((Account) _r1_o).balance = _r0.i;
    return;
\}
\end{xcode}
\end{graybox}
In particular, note that the code in line \ref{CSHARP_ADD_INT} was
generated by an XSL template identical to the aforementioned XSL
template for the \texttt{$<$dex:add-int$>$} instruction in the C
backend. Of course, other XSL templates for the C\# backend differ
from the C backend. In this section we highlight those differences.

First, templates for generation of register variables are now based on
\texttt{org.xmlvm.Element} (line \ref{CSHARP_PRIMITIVE_TYPE}); the
latter is an aligned C\#-struct that imitates a C-union and reflects
the different data types that registers may contain:

\noindent
\begin{graybox}
\begin{xcode}[label=C\#]
using global::System.Runtime.InteropServices;
namespace org.xmlvm \{
    [StructLayout(LayoutKind.Explicit)]
    public struct Element \{
	[FieldOffset(0)]
	public int i;	
        [FieldOffset(0)]
	public float f;
	[FieldOffset(0)]
	public double d;
	[FieldOffset(0)]
	public long l;
    \}
\}
\end{xcode}
\end{graybox}

Second, variables representing registers that store object references
have to be defined separately, since C\# does not allow alignment or
overlap of object fields with non-object fields for security reasons. They are mapped to
variables of type \texttt{System.Object} (line \ref{CSHARP_OBJ_REF}),
since all such Dalvik registers are of type \texttt{java.lang.Object}.

Moreover, field and method names have to be mangled to escape C\#
keywords (such as "out" and "internal"), which are not Java keywords,
and to escape \$s in Java identifiers, which are not allowed in C\#
identifiers.  Additional name mangling is needed to account for C\#
not allowing clashes of method and field identifiers.

Further attention has to be given to differences between the Java and
C\# object models \cite{csharp}; for example, a C\# method does not
override its parent unless it is annotated with the \texttt{override}
modifier and its parent is annotated with \texttt{virtual}.
Therefore, XMLVM analyzes the object hierarchy and identifies Java
methods that override their base class methods, such as:

%AP: BTW: why not simply all public/protected methods with 'override'?
% This way you don't need an elaborate analysis. Was there a reason for
% that? If so, please mention it in the preceeding paragraph.

\noindent
\begin{graybox}
\begin{xcode}[label=InvestmentAccount.java]
public class InvestmentAccount extends Account \{
    public void deposit(int amount) \{
        //...
    \}
\}
\end{xcode}
\end{graybox}
and annotates them internally by adding a special XML attribute
\texttt{@isOverride} to the existing \texttt{$<$vm:method$>$} tag.
%
%and annotates them internally with a special attribute:
%\begin{xcode}[label=XMLVM]
%<vm:xmlvm ...>
%  <vm:class name="InvestmentAccount" 
%            extends="Account" ...>
%    <!-- ... -->
%    <vm:method name="deposit" \textbf{isOverride="true"} ...>
%      <!-- ... -->
%    </vm:method>
%  </vm:class>
%</vm:xmlvm>
%\end{xcode}
Subsequently, the stylesheet for the C\# backend transforms this
attribute into the required \texttt{override} modifier:

\noindent
\begin{graybox}
\begin{xcode}[label=Generated C\#]
public class InvestmentAccount: Account \{
    //...
    public \textbf{override} void deposit(int n1) \{
        //...
    \}
\}
\end{xcode}
\end{graybox}

Moreover, C\# does not allow covariant return types which is
permissible in Java.  
For example, consider an \texttt{InvestmentBank} class 
that overrides an \texttt{openAccount()} method of a base \texttt{Bank} class:

\noindent
\begin{graybox}
\begin{xcode}[label=Covariant return example in Java]
public class Bank \{
    //...
    public \textbf{Account} openAccount() \{
	return new Account();
    \}
\}

public class InvestmentBank extends Bank \{
    @Override
    public \textbf{InvestmentAccount} openAccount() \{\label{CSHARP_COVARIANT_RETURN}
	return new InvestmentAccount();
    \}
\}
\end{xcode}
\end{graybox}

C\# would not allow the method to return \texttt{InvestmentAccount} on
line \ref{CSHARP_COVARIANT_RETURN}. Covariant returns are common
programming pattern in Java and are frequently used in the definition
of the J2SE API.
% Similarly it would not allow the
%\texttt{append} methods of \texttt{java.io.PrintStream} to return the
%type \texttt{PrintStream}, since the overridden \texttt{append}
%methods of its interface \texttt{java.lang.Appendable} returns the
%type \texttt{Appendable}.
%
Fortunately, it is possible to overcome this problem by simply
generating \texttt{System.Object} return types for all methods
returning object references, since Dalvik registers holding object
references are always mapped to C\# variables of type
\texttt{System.Object}:

\noindent
\begin{graybox}
\begin{xcode}[label=Generated C\#]
public class Bank: java.lang.Object \{
    //...
    public virtual \textbf{System.Object} openAccount() \{
        global::System.Object _r0_o;
        _r0_o = new Account();
        //...
        return _r0_o;
    \}
\}

public class InvestmentBank: Bank \{
    //...
    public override \textbf{System.Object} openAccount() \{
        global::System.Object _r0_o;
        _r0_o = new InvestmentAccount();
        //...
        return _r0_o;
    \}
\}
\end{xcode}
\end{graybox}

Furthermore, Java allows interfaces to have static fields, which is
not allowed in C\#.  The solution to this problem is three
folded.  First, to each Java interface, XMLVM generates an additional
C\# abstract class which contains the static fields and
initializes them in its static constructor. Next, the transformation
checks whether the the \texttt{@class-type} attribute of each
\texttt{$<$dex:sget$>$} tag is an interface, in which case it
retrieves the field value from the adjunct abstract class.  Similarly,
a new value is assigned to the field of the adjunct abstract
class in case the \texttt{@class-type} attribute of an
\texttt{$<$dex:sput$>$} is found to be an interface.  Finally, the
transformation implements inheritance of such static fields, via a
top-down breadth-first analysis of the class-hierarchy.  For each
interface, and each of its static fields, the transformation adds
the field to each implementing class and interface, if it is not
already overridden by this implementation. The top-down analysis
guarantees that fields from higher levels are accumulated before
their addition to the next generation.

% discuss abstract classes not implementing their interface methods

The aforementioned transformation of Java byte codes to C\# is fully
Java compliant.  Besides the aforementioned differences in the object
model, the transformation also handles Java exceptions and arrays (by
wrapping them inside their C\# counterparts), inner classes, local and
anonymous classes, reflection instructions (such as
\texttt{$<$dex:const-class$>$}) and string creation instructions (such
as the \texttt{$<$dex:const-string$>$}). The transformation of the
latter instruction converts the string value into a C\# char array and
calls the appropriate constructor of the generated
\texttt{java.lang.String} on the target platform, if the string does
not already exist in a special constant-pool data structure (to avoid
duplication of strings).

%AP: the following is explained in section 5.1
%
% probably change the following to partial classes:
%To facilitate native implementation, the transformation generates a
%placeholder method for each native method, with two comments marking
%its beginning and end. XMLVM looks for previously written native
%implementation of such a method by searching for similar markers in
%the output directory.  If found, such an existing implementation is
%injected between the marker comments of the newly generated code.

\section{J2SE API Mapping}
\label{SEC_J2SE}

The previous section described the lower layer byte-code
cross-compilation from Java to C and C\# code. A Java application
typically depends on external libraries. In the next section, we
describe mapping of APIs specific to Android applications, such as
application lifecycle and user interface programming, whereas in this
section we focus on mapping of general J2SE APIs to the target
platform, such as data structures and reflection APIs. A prerequisite
for supporting J2SE API is the ability to access a platform's
native layer. This is described in Section \ref{SEC_NATIVE}.  Since
XMLVM does not rely on the availability of a JVM, all classes that an
application depends on need to be bundled in the executable. In
Section \ref{SEC_DEPEND} we describe a mechanism by which the
transitive closure of all dependent classes can be determined.

% However, this results in many redundant dependencies and, moreover,
% some parts of any J2SE implementation cannot be written purely in
% Java, since they have to access the underlying system. In this section
% we address these issues: in subsection \ref{SEC_NATIVE} we describe
% the mapping of native implementation to the target platform, whereas
% in subsection \ref{SEC_DEPEND} we describe how XMLVM optimizes the
% size of the cross compiled set of Java classes, removing redundant
% dependencies.

% The basic idea the middle layer of the framework is responsible for
% cross-compilation of J2SE APIs, such as data structures, to the
% development language used on the target platform.  To this end, XMLVM
% simply applies the aforementioned language cross-compilation to the
% Java implementation of J2SE provided by the open source Apache
% Harmony.

\subsection{Java Native Interface}
\label{SEC_NATIVE}

Much of the J2SE API is typically implemented in Java itself. E.g.,
data structures such as \texttt{java.util.ArrayList} or
\texttt{java.util.HashMap} are purely implemented in Java. The
Java-based implementation of J2SE API is simply cross-compiled to the
target platform in the same way as described in the previous section.
XMLVM leverages the Open Source project Apache Harmony for this
purpose. Certain J2SE API needs to access the native layer of a
platform and can consequently not be implemented in Java itself.
Examples of such API are file I/O, socket communication, and
multi-threading. To facilitate their implementation, the JVM provides
a bridge for calling (and being called by) code implemented in other
languages -- the \emph{Java Native Interface} (JNI). The standard JNI
workflow consists of declaring a Java method as native, implementing
it natively, compiling the native library and loading the library in
the JVM at runtime. XMLVM provides a similar solution; however, due
to the lack of a JVM, native code cannot be loaded dynamically, but
rather at compile and link time. Thus, for each native method, the
stylesheet for the C backend generates a call to a wrapper function
providing a Posix-based implementation, whereas the stylesheet for the
C\# backend generates special markers between which existing .NET
implementation is injected.

XMLVM has implemented a large subset of such native methods for each
target platform; in fact, it is large enough to support the entire
J2SE reflection API and many other Java APIs required for cross
compilation of most Android applications to iOS and to WP7, such as
those mentioned in Section \ref{SEC_API_MAPPING}.

As an example, consider the implementation of the
\texttt{currentTimeMillis} method of \texttt{java.lang.System}; it has
to access the underlying system and, hence, it is declared as a native
method:

\noindent
\begin{graybox}
\begin{xcode}[label=J2SE API]
package java.lang;

public final class System \{
    //...
    public static native long currentTimeMillis();
\}
\end{xcode}
\end{graybox}

The C backend of the lower level byte-code cross compilation of XMLVM
generates a call to
\texttt{java\_lang\_System\_currentTimeMillis\_\_}; the latter was
implemented as part of the native library provided by XMLVM using
Posix's \texttt{gettimeofday}:

\noindent
\begin{graybox}
\begin{xcode}[label=C implementation]
JAVA_LONG java_lang_System_currentTimeMillis__()
\{
    //XMLVM_BEGIN_NATIVE[java_lang_System_currentTimeMillis__]
    struct timeval now;
    \textbf{gettimeofday(&now, NULL);}
    JAVA_LONG msec = ((JAVA_LONG) now.tv_sec) * 1000;
    msec += now.tv_usec / 1000;
    return msec;
    //XMLVM_END_NATIVE
\}
\end{xcode}
\end{graybox}

On the other hand, the C\# backend generates special markers between
which .NET implementation is injected:

\noindent
\begin{graybox}
\begin{xcode}[label=C\# implementation]
namespace java.lang \{
  public partial class System: java.lang.Object \{
      // ...
      private static DateTime baseTime =
                 new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
      public static long currentTimeMillis() \{
         return (long)(DateTime.UtcNow - bastTime).TotalMilliseconds;
      \}
  \}
\}
\end{xcode}
\end{graybox}

As another example, the C backend maps the Java thread API via native
methods to pthreads while the C\# backend leverages the
\texttt{System.Threading} package. Java offer reflection via classes
\texttt{Field} and \texttt{Method} in the \texttt{java.lang.reflect}
package, whose native methods are implemented by adaptating the .NET
methods of \texttt{System.Reflection.FieldInfo} and
\texttt{System.Reflection.MethodInfo}, respectively. Similarly,
\texttt{java.lang.Class} wraps \texttt{System.Type}. Since the C
programming language does not offer its own object model, the C
backend of XMLVM generates sufficient meta-data during
cross-compilation to implement the Java object model.

%AP the paragraph below is not sufficiently explained. Why are
% Java constructors not mapped to C\# constructors?
%
%However, methods
%of the \texttt{Constructor} class are not wrapped around the methods
%of \texttt{ConstructorInfo}, since Java constructors are not mapped to
%C\# constructors; the Java compiler maps Java constructors to special
%\texttt{<init>} methods, which are then mapped by XMLVM to the target
%platfrom as any other method; hence, \texttt{Constructor} is
%implemented as a wrapper around the methods of the \texttt{MethodInfo}
%for the \texttt{<init>} method generated by the compiler.

% maybe discuss C\# vs C implementation of TIBs
\subsection{Dependency Analysis}
\label{SEC_DEPEND}

A standard JVM loads classes at runtime on demand. Whenever the
application references a class, it is loaded via a so-called
\emph{class loader}. E.g., a regular console-based ``Hello World''
application in Java loads more than 300 classes from the J2SE library
when executed on a JVM. Since XMLVM does not rely on a JVM on the
target platform, all classes that an application depends on need to be
bundled in the final executable. One obvious solution would be to
include all classes part of J2SE. Considering that version 6 of the
J2SE consists of over 30,000 classes, this is not feasible.

Generally it is not decidable whether an application depends on a
particular class or not. Matters are further complicated by Java
reflection that makes it impossible for a tool to determine
dependencies. However, XMLVM performs a conservative dependency
analysis to reduce the size of the final executable.  XMLVM analyzes
byte code instructions of each class for their dependencies. As a
first step, XMLVM removes classes which are not reachable from the
application classes in the dependency graph.

%AP: this is not true. With the use of reflection you can easily
% reference a class that was not determined to be reachable during
% the dependency analysis.
%The resulting weakly connected component is a safe set of
%classes whose cross-compilation to the target platform guarantees
%correct execution of the application.

Unfortunately, this connected complement often results in a very large
set of classes; for example, a even simple console based Hello World
references classes from AWT (Abstract Windowing Toolkit) and Swing,
which are never really reached during execution.  The reason is that
some conditional branch that is never reached, or some bytecode
instruction in a method that is never called, may reference an
unnecessary dependency, which can escalate to entire redandant
packages, such as AWT and Swing

Although The minimal set of dependencies spanned by all execution
paths is not decidable, XMLVM attempts to reduce the size of the
cross-compiled set by marking some classes as \textit{red} if it is
known that they will never be needed. Examples of red classes are
classes in the AWT and the Swing packages; the both of which are not
needed in a mobile application, since Android and other mobile
platforms employ their own GUI API. On the other hand, classes that
are known to lie on the execution path of most applications are marked
as \textit{green}.  XMLVM extends these initial subsets to a full
red-green classification of the class dependency graph.  This results
in a list of red classes that XMLVM does not cross-compile to the
target platform. If a green classes makes use of a red class, XMLVM
will emit a runtime exception to signal an unsatisfied dependency.

% explain we want to 1. minimize no. of classes- efficiency 2. minimize number of native methods

During this classification phase, developers may add and remove more
classes to the initial subsets, based on their knowledge of the
application logic. For instance, they may add a class to the initial
green subset if they know it is accessed dynamically via reflection
API (which the dependency analysis cannot see).  To facilitate this
phase, XMLVM also presents developers with suggestions for red
coloring (dependency removals) that are sorted by the potential gain
and they can stop the phase when the potential gain from further
dependency removals is small.

Furthermore, XMLVM allows a finer red-green classification of the
method dependency graph, rather than class dependencies. As a
consequence, some unused methods may be removed from a class, further
reducing the size of the executable. Developers are again presented
with suggestions for coloring of initial method subsets and XMLVM
extends these to a full red-green classification.  Byte code
instructions relating to the red methods are marked with special XML
attribute, causing the stylesheets to generate runtime exception
rather than native code.

% Hereafter, we describe the aforementioned extension of the initial red
% green coloring to a full red-green classification of the dependency
% graph (i.e. a graph cut).

\section{API Mapping}
\label{SEC_API_MAPPING}

While the previous section focused on cross-compiling Java programs to
C\# and C, we discuss the mapping of the Android API to the API of the
respective target platform in the following. This section is organized
as follows: Section \ref{SEC_API_MAPPING_OVERVIEW} provides an
overview of the different layers used for the API mapping and
discusses the functions they provide and their APIs. Section
\ref{SEC_API_MAPPING_WRAPPER_WP7} presents the implementation details
of the wrapper library layer for WP7 while Section
\ref{SEC_API_MAPPING_WRAPPER_IOS} shows the same for iOS.
Finally, \ref{SEC_API_MAPPING_ACL} discusses the implementation
details of the Android Compatibility Library and
the Native Adapter Library.

\begin{figure*}[htb]
\begin{center}
\includegraphics[width=12cm]{android2others}
\caption{\label{FIG_XMLVM_LAYERS} (a) Classic Android Application 
(b) Android Application running on WP7
(c) Android Application running on iOS.}
\end{center}
\end{figure*}


\subsection{Overview}
\label{SEC_API_MAPPING_OVERVIEW}

Figure \ref{FIG_XMLVM_LAYERS} shows a classic Android application
versus the layer model of XMLVM. While a classic Android application
makes direct use of the underlying native platform, the mapping of an
Android application to a different platform is divided into several
different layers.

The highest level of the XMLVM layer model is the \emph{Android
  Compatibility Library (ACL)}.  It offers the same API as the Android
platform, but supports multiple underlying platforms through the use of
our \emph{Common Device API}. The Android Compatibility Library
contains the implementation of all parts which can be solved in a
platform independent manner.  Amongst others this includes APIs such
as the layout manager, parsing of \texttt{AndroidManifest.xml} or the
Android Activity lifecycle. Significant portions of the ACL's
implementation is taken directly from the official Android Open Source
code base.

%!!! The following should have been mentioned in the section on libraries
%
%However, Android also uses APIs which are not Android specific, but
%part of the standard Java SE APIs.  The most common are data
%structures and other parts of \texttt{java.util.*}. Like Android
%itself we use the project Apache Harmony, an Open Source
%implementation of Java SE, to provide these APIs. Since Apache Harmony
%is itself written in Java, it is simply cross-compiled with XMLVM.

\emph{Native Adapter Libraries (NAL)} are responsible for adapting
differences between Android's API and the API of the underlying
platform and implement our specified Common Device API.  The Common
Device API is exposing all platform dependent native functionality
needed by the ACL.  Typical examples for exposed native functionality
are UI widgets, like buttons or text fields, or sensor API. The NAL
hides platform specific API from the ACL. Each target platform
requires its own specific NAL.

\emph{Wrapper libraries} are the lowest level of the XMLVM layer model
and are needed if the underlying platform does not expose its API via
Java. If a platform uses a different programming language, the wrapper
libraries expose the native API in Java. C\# WP7 API, or Objective-C
Cocoa Touch API, are represented as a Java API, allowing the NAL
(which is written in Java) to interact with native functionality. In
the following we first explain the wrapper libraries for WP7 and iOS
and then discuss the details of the ACL and the NAL.


\subsection{Wrapper Library for WP7}
\label{SEC_API_MAPPING_WRAPPER_WP7}

The wrapper library for WP7 exposes the C\# based API through Java.
C\# offers a variety of features like properties, operator overloading
or delegates and events, that are not supported by the Java
object model. In order to represent these constructs, they are
emulated by using POJOs with the goal in mind to represent the
original C\# API as closely as possible. To illustrate this process,
consider the original API of WP7:

\begin{xcode}[label=C\#: Original Button API in WP7]
namespace System.Windows \{
  public delegate void RoutedEventHandler(\label{CODE_DELEGATE}
    Object sender,
    RoutedEventArgs args
  )
\}

namespace System.Windows.Controls \{
  public class Button \{
    public String Content \{ get; set; \}\label{CODE_CONTENT}
    public event RoutedEventHandler Click;\label{CODE_CLICK}
    //...
  \}
\}
\end{xcode}

The example is simplied for the purpose of this paper. Setting the
label of a button requires the setting of an appropriate property called
\texttt{Content} (line \ref{CODE_CONTENT}). An application can install
a click listener via the C\# event model (line \ref{CODE_CLICK}). The
WP7 defines a delegate called \texttt{RoutedEventHandler} for this
purpose (line \ref{CODE_DELEGATE}). This was also shown in the WP7
version of ``Say Hello'' in Section \ref{SEC_SAY_HELLO_WP7}.

Based on the C\# API, the following listing shows the derived Java version of
the button API as exposed by XMLVM's wrapper library for WP7:

\begin{xcode}[label=Java: WP7 Button Wrapper]
package Compatlib.System.Windows;

@XMLVMSkeletonOnly
public class RoutedEventHandler \{
    public void __add(RoutedEventHandler handler) \{\}
    public void __fire(Object sender, RoutedEventArgs args) \{\}
\}


package Compatlib.System.Windows.Controls;

@XMLVMSkeletonOnly
public class Button \{
    public void setContent(String content) \{\}
    public RoutedEventHandler Click;
    //...
\}
\end{xcode}

As can be seen in the code excerpt above, the implementation of the
class is left empty since its only purpose is to provide a Java API
that can be used by the implementation of the NAL. The C\# event and
delegate are emulated by the Java class \texttt{RoutedEventHandler}.
Operator overloading is mimicked by specially named methods
representing the overloaded operator, like \texttt{\_\_add} for += in
the example above. Properties, like \texttt{Button.Content}, are
represented by appropriate getter/setter methods. The package name of
a wrapper class is the C\# namespace of the class prefixed with
\texttt{Compatlib} to avoid conflicts after cross-compilation.

Wrapper classes are marked with an \texttt{@XMLVMSkeletonOnly}
annotation and are treated special by XMLVM's cross-compiler. The
implementation of a method in a wrapper class is ignored and instead
special comment markers are emitted. The programmer can inject
manually written code between these comment markers. This code is
tying the wrapper class together with the native class it wraps. The
following code excerpt demonstrates this concept for the
\texttt{Button} class.

\begin{xcode}[label=C\#: Cross-compiled WP7 Button Wrapper]
using native = System.Windows.Controls;
namespace Compatlib.System.Windows.Controls \{
  public class Button \{
    public Compatlib.System.Windows.Controls.RoutedEventHandler Click;

    public virtual void setContent(java.lang.String n1) \{
      //XMLVM_BEGIN_WRAPPER
      \textbf{wrapped.Content = Util.toNative(n1);}\label{CODE_SET_CONTENT}
      //XMLVM_END_WRAPPER
    \}

    //XMLVM_BEGIN_WRAPPER
    \textbf{public native.Button wrapped = new native.Button();}\label{CODE_NATIVE_BUTTON}

    \textbf{public Button \{}
      \textbf{wrapped.Click += ClickHandler;}\label{CODE_REG_HANDLER}
    \textbf{\}}

    \textbf{public void ClickHandler(object sender, RoutedEventArgs args) \{}
      \textbf{Click.__fire(Util.toWrapper(sender), Util.toWrapper(args));}\label{CODE_FIRE}
    \textbf{\}}
    //XMLVM_END_WRAPPER

    //...
  \}
\}
\end{xcode}

Note that the wrapper class above is not implementing the widget
itself, but only wraps the native WP7 API \texttt{Button} class (line
\ref{CODE_NATIVE_BUTTON}). Code between the
\texttt{XMLVM\_BEGIN\_WRAPPER} and \texttt{XMLVM\_END\_WRAPPER}
comments is manually written C\# code which gets injected on either
method- or class-level during cross-compilation. The comment markers
allow the manually written code to be automatically migrated to an
updated version of the generated file if it should become necessary to
regenerate the wrappers. The code outside the comment markers is
emitted by the stylesheet as explained in Section \ref{SEC_BYTE_CODE}.

Communication between the native API and the wrapper library can
happen in both directions. Method \texttt{setContent()} is an example
for communication from the wrapper library to the native widget (down-call). The
code above converts a \texttt{java.lang.String} instance to a native
C\# string via a helper function and sets the \texttt{Content}
property of the wrapped button to the converted string (line
\ref{CODE_SET_CONTENT}).

Events represent communication in the opposite direction: from the
native widget to the wrapper library (up-call). During construction of the
wrapper we register a generic event handler function for the
\texttt{Click} event of the wrapped button (line
\ref{CODE_REG_HANDLER}).  When a native click event is received our
event handler function converts the accompanying parameters to wrapper
library classes. Afterwards it fires off the \texttt{Event} class in
the wrapper library which emulates C\# events as POJOs (line
\ref{CODE_FIRE}).

To summarize, the purpose of wrapper libraries is to expose a
platform's native, C\# API in Java. Wrapper libraries are responsible
for the communication between the native layer and Java code. We
achieve that by injecting hand-written C\# code, responsible for this
communication, into them during cross-compilation.

\subsection{Wrapper Library for iOS}
\label{SEC_API_MAPPING_WRAPPER_IOS}

The wrapper library for iOS follows the same pattern as for WP7. Since
the native language of iOS is Objective-C, the wrapper library for
this platform needs to expose Objective-C API through Java. Consider
the Objective-C API for \texttt{UIButton} in iOS:

\begin{xcode}[label=Objective-C: Original UIButton API in iOS]
@interface UIButton

- (void)setTitle:(NSString *)title forState:(UIControlState)state;\label{CODE_TITLE}
- (void)addTarget:(id)target action:(SEL)action
        forControlEvents:(UIControlEvents)controlEvents;\label{CODE_TARGET}
//...

@end
\end{xcode}

The API shown above allows to set the title for a \texttt{UIButton}
(line \ref{CODE_TITLE}) and the installation of a click listener (line
\ref{CODE_TARGET}). Passing a reference to a click listener requires
two parameters in iOS: a reference to an Objective-C object (parameter
\texttt{target}) and a selector that should be invoked on that target
(parameter \texttt{action}). This is a common pattern in iOS due to
the dynamic nature of Objective-C. When deriving a Java API, we have
opted to introduce a strongly typed interface called
\texttt{UIControlDelegate} as can be seen in the following code
excerpt:


\begin{xcode}[label=Java: iOS UIButton Wrapper]
@XMLVMSkeletonOnly
public interface UIControlDelegate \{
    public void raiseEvent(UIControl sender, int uiControlEvent);
\}

@XMLVMSkeletonOnly
public class UIButton \{
    public void setTitle(String title, int uiControlState) \{\}
    public void addTarget(UIControlDelegate delegate,
                          int uiControlEvent) \{\}
    //...
\}
\end{xcode}

Interface \texttt{UIControlDelegate} has no correponding counterpart
in the Objective-C API for iOS and was introduced soley for the
purpose of creating a natural looking Java API. Classes and interfaces
have the same \texttt{@XMLVMSkeletonOnly} annotation as discussed in
the previous section. The XMLVM cross-compiler will generate C files
with special comment markers that allow the injection of manually
written code. The following code listing shows the wrapper code for
method \texttt{setTitle()}:

\begin{xcode}[label=C: Cross-compiled iOS UIButton Wrapper]
void UIButton_setTitle(JAVA_OBJECT me, JAVA_OBJECT n1, JAVA_INT n2)
\{
    //XMLVM_BEGIN_WRAPPER
    \textbf{XMLVM_VAR_THIZ;}\label{CODE_THIZ}
    \textbf{[thiz setTitle:Util_toNSString(n1) forState:n2];}\label{CODE_CALLING_IOS}
    //XMLVM_END_WRAPPER
\}
\end{xcode}

The iOS backend of XMLVM offers a helper macro called
\texttt{XMLVM\_VAR\_THIZ} (line \ref{CODE_THIZ}) that associates a C
object (parameter ``\texttt{me}'') with the wrapped Objective-C
instance that can be referred to via a new variable ``\texttt{thiz}''.
The latter is used to invoke the actual \texttt{setTitle:forState:}
selector of the wrapped iOS \texttt{UIButton} (line
\ref{CODE_CALLING_IOS}).

Doing an up-call (such as a button click) is more complex. The reason
for this is that iOS has no knowledge of XMLVM's code generation. The
\texttt{addTarget:forState:} message of \texttt{UIButton} expects an
Objective-C object as the destination of an up-call. For this reason
the wrapper library for iOS needs to include special helper classes
that act as a bridge between the Objective-C world and the
cross-compiled C code:

\begin{xcode}[label=Objective-C: UIControlDelegateWrapper helper]
//XMLVM_BEGIN_IMPLEMENTATION
@implementation UIControlDelegateWrapper\label{CODE_UICONTROLDELEGATEWRAPPER}

- (id) initWithDelegate:(JAVA_OBJECT) delegate_
                       :(JAVA_OBJECT) control_
\{
    [super init];
    self->delegate = delegate_;
    self->control = control_;
    return self;
\}


- (void) raiseEvent:(UIControl*) control :(int)event\label{CODE_RAISE_EVENT}
\{
    Func_VOOI toCall = self->delegate->tib->
         itable[XMLVM_ITABLE_IDX_UIControlDelegate_raiseEvent];
    toCall(self->delegate, self->control, event);\label{CODE_CALLBACK}
\}

@end
//XMLVM_END_IMPLEMENTATION

void UIButton_addTarget(JAVA_OBJECT me, JAVA_OBJECT n1, JAVA_INT n2)
\{
    //XMLVM_BEGIN_WRAPPER
    \textbf{XMLVM_VAR_THIZ;}
    \textbf{UIControlDelegateWrapper* delegateWrapper =}
    \textbf{      [[UIControlDelegateWrapper alloc] initWithDelegate:n1:me];}\label{CODE_CREATE_CDW}
    \textbf{[thiz addTarget:delegateWrapper action:@selector(raiseEvent::)}
    \textbf{      forControlEvents:n2];}\label{CODE_CALL_ADD_TARGET}
    //XMLVM_END_WRAPPER
\}
\end{xcode}

Objective-C class \texttt{UIControlDelegateWrapper} (line
\ref{CODE_UICONTROLDELEGATEWRAPPER}) serves as this bridge. Whenever a
click listener is registered with a \texttt{UIButton}, an instance of
this class is created (line \ref{CODE_CREATE_CDW}). This instance is
used as the recipient of \texttt{UIButton} click events (line
\ref{CODE_CALL_ADD_TARGET}). When a user clicks on the
\texttt{UIButton}, iOS will call \texttt{raiseEvent::} of
\texttt{UIControlDelegateWrapper} (line \ref{CODE_RAISE_EVENT}). The
implementation of this method will retrieve the appropriate function
pointer via the interface jump table of the TIB and then call the
cross-compiled Java code of the click listener (line
\ref{CODE_CALLBACK}).


\subsection{Android Compatibility Library  (ACL) and Native Adapter Libraries  (NAL)}
\label{SEC_API_MAPPING_ACL}

The purpose of the ACL is to offer the Android API to an application
while supporting multiple different platforms for its implementation.
The codebase from the original Android sources used for the
implementation is modified to use the Common Device API exposed by the
Native Adapter Libraries. The Native Adapter Libraries bind the
Android API to the previously discussed wrapper libraries.

In addition to the Android codebase, Harmony is used to provide the
J2SE APIs.  The majority of Harmony's J2SE APIs are themselves
written in Java. A useful subset of this API is simply cross-compiled
as well to the language of the target platform and used as part of the
compatibility library. XMLVM calculates dependencies to J2SE API at
compile time and automatically includes needed classes in the
cross-compilation process as described in Section \ref{SEC_J2SE}.

On the system-level, Apache Harmony uses native Java methods to access
functionality of the underlying operating system. These methods are
implemented by using native functionality of the target platform (e.g.
WP7 API on WP7 or Posix API on iOS).  As with wrappers, the code for
the implementation of native methods gets injected during
cross-compilation.

As the codebase of the Android Compatibility Library is shared between
all supported platforms we try to keep all functionality that does not
necessarily need access to native capabilities in this layer. For some
tasks, like XML parsing, native support would exist on the supported
platforms, but to keep the Common Device API as small as possible we
chose to implement those parts purely in Java as well. This minimizes
the effort needed to add new platforms because these APIs are
automatically available through cross-compilation.
% On the other hand performance of the 
%cross-compiled code might be worse than the one of built-in native capabilities.

Due to the fact that XMLVM supports multiple different platforms,
functionality from the Android API must be mapped to several different
native platforms. To achieve this the ACL is written platform
independent and uses platform specific Native Adapter Libraries that
implement an API called Common Device API. Due to the fact that all
Native Adapter Libraries implement the same API the actual underlying
platform is completely hidden from the ACL.

The following code excerpt shows how an \texttt{android.widget.Button}
is mapped to the \texttt{Button} from the WP7 wrapper library
explained in the previous section:

\begin{xcode}[label=Java: excerpts from ACL and NAL]
// \textbf{Android Compatibility Library}
package android.widget;

public class Button \{
  private ButtonAdapter adapter;
  // ...
  public Button(Context c) \{
    AdapterFactory f = FactoryFinder.getAdapterFactory();\label{ACL_GET_ADAPTER_FACTORY}
    adapter = f.createButtonAdapter();
  \}

  public void setText(String string) \{
    adapter.setText(text);
  \}	
\}

// \textbf{WP7 Native Adapter Library}
public class WP7AdapterFactory implements AdapterFactory \{
  // ...
  public ButtonAdapter createButtonAdapter() \{
    return new WP7ButtonAdapter();
  \}
\}

public class WP7ButtonAdapter implements ButtonAdapter \{
  Compatlib.System.Windows.Controls.Button wrapper;
  // ...
  public void setText(String string) \{
    wrapper.setContent(string);\label{WP7_NAL_SET_TEXT}
  \}
\}

// \textbf{Cocoa Touch Native Adapter Library}
public class IOSButtonAdapter implements ButtonAdapter \{
  UIButton wrapper;
  // ...
  public void setText(String string) \{
    wrapper.setTitle(text, UIControlState.Normal);\label{COCOA_NAL_SET_TEXT}
  \}
\}
\end{xcode}

To communicate with an underlying platform the ACL uses the \texttt{FactoryFinder} to
get an instance of an \texttt{AdapterFactory} (line \ref{ACL_GET_ADAPTER_FACTORY}). The \texttt{FactoryFinder} will
instantiate a platform specific \texttt{AdapterFactory}, in case of WP7 a \texttt{WP7AdapterFactory}.
By using the \texttt{AdapterFactory} to instantiate adapter classes the ACL does not know
which underlying platform it uses. The \texttt{AdapterFactory} is implemented for every
supported platform and instantiates adapter classes. Adapter classes are responsible
for translating between Android API and native API exposed by the wrapper library.
In the very simple case above the \texttt{WP7ButtonAdapter} translates from the Android API method
\texttt{setText} to the equivalent WP7 API method \texttt{setContent()} (line \ref{WP7_NAL_SET_TEXT}). The class
\texttt{IOSButtonAdapter} shows the same adapter for iOS. In this case the adapter translates
from the Android \texttt{setText()} method to the \texttt{setTitle()} method of the iOS \texttt{UIButton} wrapper (line \ref{COCOA_NAL_SET_TEXT}).

Adapters are responsible for a variety of simple tasks like converting units or method names.
In more complicated cases, where no equivalent of an Android class is available on the
native platform, they emulate the class by using several different wrapper classes.

These abstractions give us the advantage that new platforms can be easily added by
implementing the specified Common Device API. Another advantage is that all supported
platforms can share code in the ACL if it is not platform-dependent. By having a clean
adapter layer both other layers, wrapper libraries and the ACL, can be developed without
any dependencies to each other.

\section{Prototype Implementation}
\label{SEC_PROTOTYPE}


We have implemented a prototype based on the ideas described in this
paper.  We make use of Dalvik eXchange (DX) \cite{dalvik:dx} and JDOM
\cite{jdom} to parse Java class files and build up the XMLVM files.
Saxon \cite{saxon} is used as the XSL engine to apply the stylesheets
that are responsible for the code generation for the different
backends.  The implementation of the Java to C/C\# cross-compilation
is fully Java compatible including exception handling, threading, and
reflection API.  However, our tool does not offer the same kind of
completeness for the API mapping, because of the complexity of the
Android API.  Some UI idioms, such as Android's hardware buttons,
cannot be mapped by a tool, but require platform-specific
implementations to make the application look and feel native for the
respective platform.  Nevertheless, the currently supported API
already allows for cross-compilation of complex applications, as shown
in the following example.

\begin{figure}
\centering
{\epsfig{file=xokoban, width=12cm}}
\caption{\label{FIG_XOKOBAN} Xokoban in the Android (top) iOS (left)
  and WP7 (right) emulator.}
\end{figure}

To demonstrate the capabilities of our tool, we used our prototype to
cross-compile Xokoban, a showcase application for Android.  Xokoban is
a remake of the classic Sokoban puzzle game in which the player has to
push objects in a maze. Xokoban makes use of a range of Android APIs
and widgets:

\begin{itemize}
\item 2D animation.
\item Alert views, buttons, checkboxes.
\item Accelerometer and swipe interface.
\item Saving/loading of preferences.
\end{itemize}

By using XMLVM, the original Android application was successfully
cross-compiled to WP7 as well as iOS devices without any changes.
When cross-compiled to WP7, XMLVM generates a turnkey VisualStudio
Windows Phone 7 project. The project generated by XMLVM contains all
cross-compiled source files and other resources, like images, but no
binaries. To compile the application and bundle it as a XAP, using
VisualStudio is necessary. Similarly, when cross-compiled to iOS,
XMLVM will generate a turnkey Xcode project that can be used to
generate an iOS executable.

Figure \ref{FIG_XOKOBAN} shows the original Android version of Xokoban
running in the Android emulator together with the cross-compiled
version for iOS and WP7 running in their respective emulators.  The
original version of Xokoban is available in the Android Market and a
cross-compiled version for iOS can be found in the Apple App Store.
The cross-compiled version for WP7 has been submitted for review to
the Windows Marketplace.

\section{Conclusion and Outlook}
\label{SEC_CONCLUSIONS}

The popularity of smartphones makes them attractive platforms for
mobile applications. However, while smartphones have nearly identical
capabilities with respect to their hardware, they differ substantially
in their programming environments. Different programming languages and
different APIs lead to significant overhead when porting applications
to various smartphones. We have chosen Android as the canonical
platform. Our byte code level cross-compiler XMLVM can cross-compile
an Android application to C and C\# code that can be run on iOS and WP7
devices, therefore not requiring the Dalvik virtual machine on the
target platform. We have demonstrated that a cross-compilation
framework is feasible, thereby significantly reducing the porting
effort. However there are capabilities offered by the Android API, e.g.
background services or being able to replace existing system applications
like the home screen or the dialer, which are not available in any similar
form on WP7 or iOS as of now. This functionality cannot be cross-compiled
by our prototype implementation.

In the future our goal is to support debugging of cross-compiled
applications.  The idea is that a Java application that was
cross-compiled with XMLVM can be debugged on the device with any
standard Java debugger such as the one integrated in Eclipse. In order
to accomplish this, an implementation of the JWDP (Java Wire Debug
Protocol) needs to be available on the target platform. We plan to use
the Open Source Maxine project \cite{ungar:05} that features a Java
implementation of JWDP. With the help of the Java-to-C/C\#
cross-compiler we will cross-compile Maxine to C or C\# to support
debugging on a iOS or a WP7 device. The challenge of this task will be
to interface with the generated C/C\# code to determine the memory
layout (such as stack and heap) at runtime.

XMLVM is available under an Open Source license at
\texttt{http://xmlvm.org}.


\section*{Acknowledgment}

This paper is an extended version of a conference publication
\cite{puder:11}. The WP7 backend of XMLVM was supported by a grant
from Microsoft Research. As with any Open Source project, XMLVM is the
result of many volunteers. We are greatly indebted to their
contributions.


\bibliographystyle{spmpsci}
\bibliography{../literature/lit}

\end{document}
